package utils;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;

public class DateUtil {
    public static void main(String[] args) {
        LocalDate localDate = LocalDate.now();
        System.out.println("localDate: " + localDate);
        localDate = LocalDate.of(2017, 07, 20);
        localDate = LocalDate.parse("2017-07-20");
        LocalDate tomorrow = LocalDate.now().plusDays(1);
        LocalDate prevMonth = LocalDate.now().minus(1, ChronoUnit.MONTHS);
        DayOfWeek thursday = localDate.getDayOfWeek(); //获取星期N
        int twenty = LocalDate.parse("2017-07-20").getDayOfMonth();
        System.out.println(thursday);

        boolean leapYear = LocalDate.now().isLeapYear();
        System.out.println("是否闰年: " + leapYear);

        boolean notBefore = LocalDate.parse("2017-07-20")
                .isBefore(LocalDate.parse("2017-07-22"));
        System.out.println("notBefore: " + notBefore);
        boolean isAfter = LocalDate.parse("2017-07-20").isAfter(LocalDate.parse("2017-07-22"));
        System.out.println("isAfter: " + isAfter);

        LocalDate firstDayOfMonth = localDate.with(TemporalAdjusters.firstDayOfMonth());
        System.out.println("这个月的第一天: " + firstDayOfMonth);
        firstDayOfMonth = localDate.withDayOfMonth(1);
        System.out.println("这个月的第一天: " + firstDayOfMonth);

        //LocalDate只判断月和日是否相同
        LocalDate birthday = LocalDate.of(2009, 07, 20);
        MonthDay birthdayMd = MonthDay.of(birthday.getMonth(), birthday.getDayOfMonth());
        MonthDay today = MonthDay.from(LocalDate.now());
        System.out.println("今天是否是我的生日: " + today.equals(birthdayMd));


        //LocalDateTime的使用
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        System.out.println("默认格式化: " + now);
        System.out.println("自定义格式化: " + now.format(dateTimeFormatter));
        LocalDateTime localDateTime = LocalDateTime.parse("2017-07-20 15:27:44", dateTimeFormatter);
        System.out.println("字符串转LocalDateTime: " + localDateTime);

        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String dateString = dateFormatter.format(LocalDate.now());
        System.out.println("日期转字符串: " + dateString);

        //已知两个日期，求相差时间
        LocalDate initialDate = LocalDate.parse("2017-07-20");
        LocalDate finalDate   = initialDate.plus(Period.ofDays(5));
        System.out.println("初始化日期: " + initialDate);
        System.out.println("加日期之后: " + finalDate);
        long between = ChronoUnit.DAYS.between(initialDate, finalDate); //initial-final
        System.out.println("差距天数: " + between);
    }
}
